import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';
import '../common/extension/string_extension.dart';
import '../service/auth_service.dart';

class LoginController extends GetxController with WidgetsBindingObserver {
  final phoneNumberController = TextEditingController();
  final passwordController = TextEditingController();

  var keyboardHeight = 0.0.obs;
  var isChecked = false.obs;
  var isPhoneLogin = false.obs;
  var showSuffix = false.obs;
  var secondsRemaining = 0.obs;
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();

    WidgetsBinding.instance.addObserver(this);

    phoneNumberController.addListener(() {
      final phone = phoneNumberController.text;
      showSuffix.value = phone.isValidPhoneNumber();
    });
  }

  void toggleCheck() {
    isChecked.value = !isChecked.value;
  }

  void startCountdown() {
    secondsRemaining.value = 120;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (secondsRemaining.value > 0) {
        secondsRemaining.value--;
      } else {
        timer.cancel();
      }
    });
  }

  Future<void> loginAsGuest() async {
    final authService = Get.find<AuthService>();
    String deviceId;
    if (GetPlatform.isWeb) {
      var uuid = const Uuid();
      deviceId = uuid.v4();
    } else {
      deviceId = await FlutterUdid.udid;
    }

    authService.login(
      loginType: LoginType.guest,
      id: deviceId,
      pwd: "",
      success: () {
        Get.back();
      },
      failure: () {
        // Handle failure
      },
    );
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();

    final bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
    keyboardHeight.value = bottomInset;
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
    phoneNumberController.dispose();
    passwordController.dispose();
    _timer?.cancel();
    super.onClose();
  }
}
